<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>点击</title>
</head>
<body onload="main()">
<canvas id="canvas" height="400" width="400">
    你的浏览器不支持WebGL，请更换新的浏览器
</canvas>
</body>

<script type='text/javascript' src='../lib/webgl-utils.js'></script>
<script type='text/javascript' src='../lib/webgl-debug.js'></script>
<script type='text/javascript' src='../lib/cuon-utils.js'></script>
<script>

	//顶点着色器
	var VSHADER_SOURCE = "attribute vec4 a_Position;\n" +
						 "void main() {\n" +
						 "    gl_Position = a_Position;\n" +
						 "    gl_PointSize = 10.0;\n" +
						 "}";
	//片元着色器
	var FSHADER_SOURCE =  "void main() {\n" +
						  "    gl_FragColor = vec4(1.0, 0.0 , 0.0, 1.0);\n" +
						  "}"
	
    function main() {
		//获得dom
		var canvas = document.getElementById('canvas');
		
		//获得gl context
		var gl = canvas.getContext('webgl');
		if(!gl){
			console.error('浏览器不支持webgl');
			return;
		}
		
		//初始化着色器
		initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE);
		
		//获取变量位置
		var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
		if(a_Position < 0){
			console.error('无法获取变量地址 a_Position');
			return;
		}
		//赋值
		gl.vertexAttrib4f(a_Position, 0.0, 0.0, 0.0, 1.0);
		document.onkeydown = function(ev) {
			onkeydownFallback(ev, gl, canvas, a_Position);
		}
		
		//指定一个清空颜色
		gl.clearColor(0.0, 0.0, 0.0, 1.0);
		gl.clear(gl.COLOR_BUFFER_BIT);
		
		gl.drawArrays(gl.POINTS, 0, 1);
    }
	
	function onkeydownFallback(ev, gl, canvas, a_Position){
		
		var val = gl.getVertexAttrib(0, a_Position);
		
		gl.clear(gl.COLOR_BUFFER_BIT);
		gl.vertexAttrib4f(a_Position, val.x + 0.1, val.y, 0.0, 1.0);
		gl.drawArrays(gl.POINTS, 0, 1);
	}
</script>
</html>